<template>
  <div v-loading="loading" class="heatmap-container">
    <div class="filter-container">
      <el-select
          v-model="timeRange"
          placeholder="选择时间范围"
          @change="fetchData"
      >
        <el-option label="最近一周" value="week"/>
        <el-option label="最近一月" value="month"/>
        <el-option label="最近一年" value="year"/>
      </el-select>
    </div>

    <v-chart :option="chartOptions" autoresize/>
  </div>
</template>

<script setup>
import {ref, computed} from 'vue';
import {ElMessage} from 'element-plus';
import * as echarts from 'echarts/core';
import {HeatmapChart} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  VisualMapComponent
} from 'echarts/components';
import {CanvasRenderer} from 'echarts/renderers';
import VChart from 'vue-echarts';
import api from '@/api';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  VisualMapComponent,
  HeatmapChart,
  CanvasRenderer
]);

const timeRange = ref('week');
const loading = ref(true);
const heatmapData = ref([]);

// 生成时间轴（两小时间隔）
const hours = Array.from({length: 12}, (_, i) => {
  const start = i * 2;
  const end = (start + 2) % 24;
  return `${String(start).padStart(2, '0')}:00-${String(end).padStart(2, '0')}:00`;
});

// 星期映射
const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const res = await api.getHeatmapData({range: timeRange.value});
    // console.log('res:', res); // 新增调试日志
    // console.log('res.data:', res.data); // 新增调试日志
    // debugger;   // 验证debugger
    heatmapData.value = res.data || [];    // 留意这里应该是res.data
  } catch (err) {
    ElMessage.error(`数据加载失败: ${err.message}`);
    heatmapData.value = [];
  } finally {
    loading.value = false;
  }
};

// 初始化加载数据
fetchData();

// 图表配置
const chartOptions = computed(() => ({
  backgroundColor: {
    type: 'linear',
    x: 0, y: 0, x2: 0, y2: 1,
    colorStops: [
      {offset: 0, color: '#f7f9fc'},
      {offset: 1, color: '#ebeff5'}
    ]
  },
  title: {
    text: `入库车流热力图（${timeRange.value}）`,
    left: 'center',
    textStyle: {
      fontSize: 18,
      color: '#2c3e50'
    }
  },
  tooltip: {
    backgroundColor: 'rgba(50,50,50,0.9)',
    borderColor: '#333',
    textStyle: {
      color: '#fff',
      fontSize: 14
    },
    extraCssText: 'box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);',
    formatter: params =>
        `${params.value[0]}<br/>时段：${params.value[1]}<br/>数量：${params.value[2]}`
  },
  xAxis: {
    type: 'category',
    data: hours,
    axisLabel: {
      color: '#666',
      fontSize: 12,
      interval: 0
    },
    axisLine: {
      lineStyle: {
        color: '#999'
      }
    },
    splitArea: {show: true}
  },
  yAxis: {
    type: 'category',
    data: [...weekDays].reverse(),
    axisLabel: {
      color: '#666',
      fontSize: 14,
      fontWeight: 'bold'
    },
    splitArea: {show: true}
  },
  visualMap: {
    min: 0,
    max: Math.max(...heatmapData.value.map(item => item.count), 10),
    calculable: true,
    orient: 'horizontal',
    left: 'center',
    bottom: 20,
    itemWidth: 20,
    itemHeight: 300,
    textStyle: {
      color: '#666'
    },
    inRange: {
      color: ['#ffeda0', '#feb24c', '#f03b20']
    }
  },
  series: [{
    name: '入库数量',
    type: 'heatmap',
    data: heatmapData.value.map(item => [
      item.time_slot,
      weekDays[item.weekday - 1],
      item.count
    ]),
    label: {
      show: true,
      color: '#2c3e50'
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }],
  animation: true,
  animationDuration: 1000,
  animationEasing: 'cubicInOut'
}));
</script>

<style scoped>
.heatmap-container {
  width: 100%;
  height: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.heatmap-container:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.filter-container {
  margin-bottom: 20px;
  text-align: center;
}

.el-select {
  width: 200px;
}

:deep(.el-input__inner) {
  border-radius: 20px;
  background: #f5f7fa;
}

:deep(.el-select__caret) {
  color: #409EFF;
}

@media (max-width: 768px) {
  .heatmap-container {
    height: 400px;
    padding: 10px;
  }
}
</style>
